// #include "LibThread.h"
#include "TcpServer.h"
#include <atomic>
#include <iostream>
#include <unistd.h>

struct myTXT
{

	std::string s = {0};
};

void pipe_cb(int fd, short event, void *ptr)
{
	char s[100] = {0};
	int n = read(fd, s, sizeof(s));

	std::stringstream ss;
	ss.write(s, n);
	std::string a = ss.str();

	std::cout << "Thread[" << std::this_thread::get_id() << "] received message: " << a << std::endl;
}

int main()
{

	std::cout << "Main Thread id [" << std::this_thread::get_id() << "]..." << std::endl;
	// TcpServer tcp;

	// pipetest

	int m_pipe[2];

	if (pipe(m_pipe) == -1)
	{

		std::cout << "???" << std::endl;
	}

	int mypipeReadFd = m_pipe[0];
	int mypipeWriteFd = m_pipe[1];

	std::thread t1([mypipeReadFd]
				   {

		struct event_base* m_base;
		m_base = event_base_new();
		struct event m_pipeEvent;
		event_set(&m_pipeEvent, mypipeReadFd, EV_READ | EV_PERSIST, pipe_cb, &m_pipeEvent);
		event_base_set(m_base, &m_pipeEvent);
		event_add(&m_pipeEvent, 0);

		event_base_dispatch(m_base);

		event_base_free(m_base);

		std::cout << "Thread[" << std::this_thread::get_id() << "] is died..." << std::endl; });

	t1.detach();

	// myTXT m;
	std::string s;

	while (1)
	{

		std::getline(std::cin, s);
		// std::cin >> s;

		if (s == "close")
			break;
		write(mypipeWriteFd, s.c_str(), s.size() + 1);
	}

	std::this_thread::sleep_for(std::chrono::seconds(1));

	close(m_pipe[0]);
	close(m_pipe[1]);

	return 0;
}
